package com.sunwayworld.basemodule.rm.environment.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.rm.environment.dao.LimsEnvironmentDataDao;
import com.sunwayworld.basemodule.rm.environment.bean.LimsEnvironmentDataBean;
import com.sunwayworld.basemodule.rm.environment.service.LimsEnvironmentDataService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsEnvironmentDataServiceImpl implements LimsEnvironmentDataService {

    @Autowired
    private LimsEnvironmentDataDao limsEnvironmentDataDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsEnvironmentDataDao getDao() {
        return limsEnvironmentDataDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsEnvironmentDataBean limsEnvironmentData = jsonWrapper.parseUnique(LimsEnvironmentDataBean.class);
        limsEnvironmentData.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsEnvironmentData);
        return limsEnvironmentData.getId();
    }

    @Override
    public JSONObject changeStatus(RestJsonWrapperBean jsonWrapperBean) {
        JSONObject req = new JSONObject();
        List<LimsEnvironmentDataBean> beanList = jsonWrapperBean.parse(LimsEnvironmentDataBean.class);
        if (beanList.isEmpty()) {
            return req;
        }
        List<Long> ids = beanList.stream().map(LimsEnvironmentDataBean::getId).collect(Collectors.toList());
        LimsEnvironmentDataBean update = new LimsEnvironmentDataBean();
        update.setProcessStatus("done");
        getDao().updateByIds(update, ids, "processStatus");

        return req;
    }
}
